import React, { useState, useEffect } from 'react';
import { Modal, Button, Input, Select, Form, Space, message, Switch } from 'antd';
import { getArrayProps, RSAencrypt } from '@/utils/utils';
import { getRoleList } from '@/services/role';
import { addAdminUser, updateAdminUser } from '@/services/admin-user';

const formItemLayout = {
  labelCol: {
    xs: { span: 20 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};
const { Option } = Select;

type AdminUserProps = {
  userInfo: ADMIN_USER_API.AdminUser;
  onClose: () => void;
  toFetchList: () => void;
};
const AdminUserItem: React.FC<AdminUserProps> = (props) => {
  const { userInfo, onClose, toFetchList } = props;
  const [form] = Form.useForm();
  const [roleList, setRoleList] = useState<ROLE_API.Role[] | []>([]);

  useEffect(() => {
    const fetchRoleList = async () => {
      const rsp = await getRoleList({ current: 1, pageSize: 100 });
      if (rsp.code === 0) {
        setRoleList(rsp.data.list);
      }
    };
    fetchRoleList();
  }, []);

  const onFinish = async (values: any) => {
    const rsp = userInfo
      ? await updateAdminUser({
          ...values,
          id: userInfo.id,
          state: userInfo.id === 1 ? 1 : values.state && userInfo.id !== 1 ? 1 : 0,
        })
      : await addAdminUser({
          ...values,
          type: 2,
          password: RSAencrypt('123456'),
          state: values.state ? 1 : 0,
        });
    if (rsp.code === 0) {
      message.success(`${userInfo ? '修改系统用户成功' : '新建系统用户成功'}`);
      onClose();
      toFetchList();
    }
  };

  return (
    <Modal
      title={userInfo ? '修改系统用户' : '新建系统用户'}
      maskClosable={false}
      visible={true}
      onCancel={onClose}
      footer={null}
    >
      <Form
        {...formItemLayout}
        form={form}
        name="adminUser"
        onFinish={onFinish}
        initialValues={
          userInfo && {
            ...userInfo,
            roles: getArrayProps(userInfo.t_roles as string[], 'id'),
          }
        }
      >
        {userInfo && (
          <Form.Item
            name="user_no"
            label="账号"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input disabled />
          </Form.Item>
        )}
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            {
              required: true,
              message: '请输入用户名',
            },
          ]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          name="phone"
          label="手机号"
          rules={[
            {
              required: true,
              message: '请输入手机号',
            },
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item name="gender" label="性别" rules={[{ required: true, message: '请选择性别' }]}>
          <Select placeholder="请选择性别">
            <Option value={1}>男</Option>
            <Option value={2}>女</Option>
            <Option value={3}>保密</Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            {
              type: 'email',
              message: '邮箱格式不正确',
            },
            {
              required: true,
              message: '请输入邮箱',
            },
          ]}
        >
          <Input />
        </Form.Item>
        {userInfo && (
          <Form.Item name="roles" label="角色" rules={[{ required: true, message: '请选择角色' }]}>
            <Select mode="multiple" style={{ width: '100%' }} placeholder="请选择角色">
              {roleList?.length > 0 &&
                roleList.map((item) => <Option value={item.id}>{item.role_name}</Option>)}
            </Select>
          </Form.Item>
        )}
        <Form.Item name="state" label="状态" valuePropName="checked">
          <Switch checkedChildren="启用" unCheckedChildren="停用" />
        </Form.Item>
        <Form.Item name="remark" label="备注">
          <Input.TextArea placeholder="请输入备注" showCount maxLength={255} />
        </Form.Item>
        <Form.Item {...tailFormItemLayout}>
          <Space>
            <Button type="primary" htmlType="submit">
              {userInfo ? '保存' : '确定'}
            </Button>
            <Button onClick={onClose}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AdminUserItem;
